//
//  SetPersonMessageVC.m
//  UDuo
//
//  Created by 铅笔 on 15/11/21.
//  Copyright © 2015年 铅笔. All rights reserved.
//

#import "SetPersonMessageVC.h"
#import "LoginViewController.h"

#import "MailboxBindingVC.h"//邮箱绑定
#import "RealNameAuthenticationVC.h"//实名认证
#import "PasswordSetVC.h"//密码管理

@interface SetPersonMessageVC ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate>
{

    UIImageView *imageView_icon;//头像
    
    UIView *contentview;
    UIView *maskingview;
    UIView *ModifyView;
    UITextField *content;
    UIButton *modifyBtn;
    UILabel * label_name;
    
}

@property (nonatomic,strong) UITableView *tableView;

@end

@implementation SetPersonMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self initWithAllSubviews];
    self.title = @"个人信息";
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark ---- 创建子视图
- (void) initWithAllSubviews
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64)];
    [self.view addSubview: self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = COLOR_EVERYVIEWBG;
    
    //退出登录
    UIButton *button_exitLogin = [[UIButton alloc] initWithFrame:CGRectMake(20, kScreenHeight-55, kScreenWidth-40, 40)];
    [self.view addSubview:button_exitLogin];
    button_exitLogin.backgroundColor = RXDColor(255, 118, 112);
    [button_exitLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button_exitLogin setTitle:@"退出登录" forState:UIControlStateNormal];
    button_exitLogin.layer.cornerRadius = 3.0;
    button_exitLogin.clipsToBounds = YES;
    
    [button_exitLogin addTarget:self action:@selector(exitLoginAction) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark --- UITableViewDatasource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *perID = @"peronsCell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:perID];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //横线
    UIView *view_line = [[UIView alloc] init];
    [cell.contentView addSubview:view_line];
    view_line.backgroundColor = RXDColor(242, 242, 242);
    
    view_line.frame = CGRectMake(0,95*PROPORTION_WIDTH, kScreenWidth, 1.0);

    NSArray *array_avatar = @[@"头像",@"昵称",@"账户安全信息",@"手机绑定",@"身份认证",@"邮箱绑定",@"密码设置"];
    
    //label
    UILabel *label_avatar = [[UILabel alloc] initWithFrame:CGRectMake(47*PROPORTION_WIDTH, 36*PROPORTION_WIDTH, 156*PROPORTION_WIDTH, 34*PROPORTION_WIDTH)];
    [cell.contentView addSubview:label_avatar];
    label_avatar.text = array_avatar[indexPath.row];
    label_avatar.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
    
    // label
    label_name = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth-31*PROPORTION_WIDTH-100, 34*PROPORTION_WIDTH, 90, 28*PROPORTION_WIDTH)];
    [cell.contentView addSubview:label_name];
    label_name.textAlignment = NSTextAlignmentRight;
    label_name.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
    label_name.tag = 100;
    
    UIImageView *imageView_arrow;
    if (indexPath.row!=0&&indexPath.row!=2&&indexPath.row!=3&&indexPath.row!=4) {
        //右侧箭头
        imageView_arrow = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-49*PROPORTION_WIDTH, 33*PROPORTION_WIDTH, 30*PROPORTION_WIDTH, 31*PROPORTION_WIDTH)];
        [cell.contentView addSubview:imageView_arrow];
        imageView_arrow.image = [UIImage imageNamed:@"return_right"];
    }
   
    if (indexPath.row == 0) {
        
        label_avatar.frame = CGRectMake(47*PROPORTION_WIDTH, 77*PROPORTION_WIDTH, 156*PROPORTION_WIDTH, 34*PROPORTION_WIDTH);
        view_line.frame = CGRectMake(0, 180*PROPORTION_WIDTH-1.0, kScreenWidth, 1.0);
        
       imageView_icon  = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-imageView_arrow.frame.size.width-50, 23*PROPORTION_WIDTH, 40, 40)];
        [cell.contentView addSubview:imageView_icon];
        
        [imageView_icon sd_setImageWithURL:[NSURL URLWithString:self.str_avatarUrl] placeholderImage:[UIImage imageNamed:@"ic_mrbang"]];
        
        imageView_icon.layer.cornerRadius = imageView_icon.frame.size.width/2;
        imageView_icon.clipsToBounds = YES;
        imageView_icon.tag = 105;
    }
    
    if (indexPath.row == 1) {
        
        NSLog(@"str_name%@",self.str_realName);
        
        if ([self.str_realName isEqualToString:@"no"]) {
            label_name.text = @"请填写";
        }
        else
        {
            label_name.text = self.str_name;
           
        }
    }
    if (indexPath.row==3) {
           label_name.text = self.str_telPhone;
    }
    if (indexPath.row==4) {
           label_name.text = self.str_realName;
    }
    
    if (indexPath.row==2) {
        
        cell.backgroundColor = COLOR_EVERYVIEWBG;
        label_avatar.frame = CGRectMake(47*PROPORTION_WIDTH, 12*PROPORTION_WIDTH, 156*PROPORTION_WIDTH, 34*PROPORTION_WIDTH);
        
        view_line.frame = CGRectMake(5, 59, kScreenWidth-10, 0);

        label_avatar.font = [UIFont systemFontOfSize:18*PROPORTION_WIDTH];
        
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 180*PROPORTION_WIDTH;
    }
    if (indexPath.row==2) {
        return 55*PROPORTION_WIDTH;
    }
    else
    {
        return 95*PROPORTION_WIDTH;
    }
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        
        //修改头像
        [self choseAvatarFromLibraryAction];
    }
    
    if (indexPath.row==1) {
        
        [self nameBtnEvent];
    }
    
    if (indexPath.row==2) {

    }
    
    if (indexPath.row==4) {
        //实名认证
//        RealNameAuthenticationVC *realNameView = [[RealNameAuthenticationVC alloc] init];
//        [self.navigationController pushViewController:realNameView animated:NO];
    }
    
    if (indexPath.row==5) {
        MailboxBindingVC *mailboxView = [[MailboxBindingVC alloc] init];
        mailboxView.str_title = @"邮箱绑定";
        [self.navigationController pushViewController:mailboxView animated:NO];
    }
    
    if (indexPath.row==6) {
        //密码管理
        PasswordSetVC *passwdView = [[PasswordSetVC alloc] init];
        [self.navigationController pushViewController:passwdView animated:NO];
    }
}

- (void) choseAvatarFromLibraryAction
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照照片", @"从相册中选择", nil];
    [sheet showInView:self.view.window];

}

#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    // 设置代理
    ipc.delegate = self;
   
    switch (buttonIndex) {
        case 0:
            // 拍照
            
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;

            
            break;
            
        case 1:
        { // 相册
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
            ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
            break;
            
        default:
            return;
            break;
    }
    
    // 显示控制器
    [self presentViewController:ipc animated:YES completion:nil];
    
}
#pragma mark - UIImagePickerControllerDelegate
/**
 *  在选择完图片后调用
 *
 *  @param info   里面包含了图片信息
 */
#pragma mark - ImagePickerController Method
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type=[info objectForKey:UIImagePickerControllerMediaType];
    //判断当前类型是图片
    if([type isEqualToString:@"public.image"])
    {
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        image=[SetPersonMessageVC imageWithImageSimple:image scaledToSize:CGSizeMake(200, 200)];
        imageView_icon.image=image;
        NSData *data;
        if(UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        [self upload:data];
//        [self saveImage:image WithName:@"userAvatar"];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        
    }
}

//保存图片
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* totalPath = [documentPath stringByAppendingPathComponent:imageName];
    
    //保存到 document
    [imageData writeToFile:totalPath atomically:NO];
    
    //保存到 NSUserDefaults
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:totalPath forKey:@"avatar"];
    //上传服务器
    [self upload:imageData];
}

//从document取得图片
- (UIImage *)getImage:(NSString *)urlStr
{
    return [UIImage imageWithContentsOfFile:urlStr];
}

- (void)upload:(NSData *)imageData
{
    if (imageView_icon.image == nil) return;
    
    // 1.创建一个管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    mgr.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/html"];
    // 2.封装参数(这个字典只能放非文件参数)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"memberid"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"];
    
    // 2.发送一个请求
    NSString *url = [NSString stringWithFormat:@"%@member/head/update",MRAPI];
    
    [mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
        [formData appendPartWithFileData:imageData name:@"head" fileName:fileName mimeType:@"image/jpeg"];
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        [BaseViewController showMessage:@"修改成功"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"errorerror%@-----%@",error,operation);
        [BaseViewController showMessage:[NSString stringWithFormat:@"%@",error]];
    }];
    
}

#pragma mark  - 缩放图片
//压缩图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
#pragma mark - 下载网络图片
-(UIImage *) getImageFromURL:(NSString *)fileURL {
    
    UIImage * result;
    
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    
    result = [UIImage imageWithData:data];
    return result;
    
}

- (void)nameBtnEvent
{
    contentview.userInteractionEnabled=NO;
    //添加蒙版
    maskingview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    maskingview.backgroundColor=[UIColor blackColor];
    //    maskingview.userInteractionEnabled=NO;
    maskingview.alpha=0.6;
    [self.view addSubview:maskingview];
    
    ModifyView=[[UIView alloc]initWithFrame:CGRectMake(40, ScreenW-140, ScreenW-80, 160)];
    ModifyView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:ModifyView];
    
    UILabel *ModifyTitle=[[UILabel alloc]initWithFrame:CGRectMake(40, 5, ModifyView.width-80, 30)];
    ModifyTitle.text=@"修改昵称";
    ModifyTitle.textColor = COLOR_BUTTON;
    ModifyTitle.textAlignment=NSTextAlignmentCenter;
    ModifyTitle.font=[UIFont boldSystemFontOfSize:18];
    [ModifyView addSubview:ModifyTitle];
    
    content=[[UITextField alloc]initWithFrame:CGRectMake(10, ModifyTitle.y+50, ModifyView.width-20, 40)];
    content.layer.masksToBounds=YES;
    content.delegate=self;
    
    content.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 40)];
    content.leftViewMode=UITextFieldViewModeAlways;
    
    content.placeholder=@"请输入昵称";
    
    content.layer.borderWidth=1;
    
    content.layer.borderColor=RXDColor(231, 231, 231).CGColor;
    content.text = self.str_name;
    
    content.tag=110;
    content.font=[UIFont systemFontOfSize:15];
    [ModifyView addSubview:content];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:content];
    
    modifyBtn=[[UIButton alloc]init];
    modifyBtn.frame=content.frame;
    modifyBtn.y=content.y+content.height+15;
    modifyBtn.layer.masksToBounds=YES;
    modifyBtn.layer.cornerRadius=20;
    [modifyBtn setTitle:@"修 改" forState:UIControlStateNormal];
    [modifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    modifyBtn.titleLabel.font=[UIFont boldSystemFontOfSize:15];
    modifyBtn.backgroundColor = COLOR_BUTTON;
    [modifyBtn addTarget:self action:@selector(modifyEvent) forControlEvents:UIControlEventTouchUpInside];
    [ModifyView addSubview:modifyBtn];
    
    
    UITapGestureRecognizer *removetap=[[UITapGestureRecognizer alloc]init];
    [removetap addTarget:self action:@selector(tap:)];
    [maskingview addGestureRecognizer:removetap];
}

#define kMaxLength 20
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location >= kMaxLength)
    {
        return NO; // return NO to not change text
    }
    return YES;
}

-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
        
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        
        if (toBeString.length > kMaxLength) {
            textField.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //开始编辑时，整体上移
    [self moveView:-100];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时，整体下移
    [self moveView:100];
}

-(void)moveView:(float)move{
    //    [UIView commitAnimations];//设置调整界面的动画效果
    [UIView animateWithDuration:0.4f animations:^{
        CGRect frame = ModifyView.frame;
        frame.origin.y +=move;//view的X轴上移
        ModifyView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark --- 移除视图

#pragma mark - 修改昵称
-(void)tap:(UITapGestureRecognizer *)tap
{
    [ModifyView removeFromSuperview];
    [maskingview removeFromSuperview];
}

#pragma mark --- 退出登录
- (void) outLoginEvent
{
    LoginViewController *loginView = [[LoginViewController alloc] init];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"memberid"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.navigationController pushViewController:loginView animated:NO];
}

#pragma mark --- 修改昵称
- (void)modifyEvent
{
    [ModifyView removeFromSuperview];
    [maskingview removeFromSuperview];
    
    contentview.userInteractionEnabled=YES;
    
    modifyBtn.userInteractionEnabled=YES;
    modifyBtn.backgroundColor=RXDColor(223, 56, 109);
    
    if (content.text.length ==0) {
        [UIView showAlertMsg:@"昵称文字不能为空" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        return;
    }
    if (content.text.length >20) {
        [UIView showAlertMsg:@"昵称文字限制20字符" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        modifyBtn.userInteractionEnabled=NO;
        modifyBtn.backgroundColor=[UIColor lightGrayColor];
        return;
    }
   
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@member/info/edit",MRAPI];
        NSDictionary *paras_info = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"nickname":content.text};
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_info success:^(id obj) {
            
            NSString *str_false = obj[@"error"];
            
            NSLog(@"nicheng%@",obj);
            
            if (str_false.length==0) {
                
                [UIView showAlertMsg:@"修改成功"];
                
                self.str_name = content.text;
                [self.tableView reloadData];
                
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }

            
        } fail:^(NSError *error) {
            [BaseViewController showMessage:@"网络请求超时"];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
    }
}

- (void)exitLoginAction
{
  
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"MR帮提示" message:@"您确定要注销该用户么" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alert.delegate=self;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self outLoginEvent];
            break;
        case 1:
            
            break;
        default:
            break;
    }
}

- (void) dealloc
{
    [self.tableView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

@end
